package com.hmall.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;
import com.hmall.common.utils.CollUtils;
import com.hmall.domain.dto.LoginFormDTO;
import com.hmall.domain.po.User;
import com.hmall.domain.vo.UserLoginVO;
import com.hmall.mapper.UserMapper;
import com.hmall.service.IUserService;
import com.hmall.utils.PasswordEncoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    @Override
    public UserLoginVO login(LoginFormDTO loginFormDTO) {
        // 1.数据校验
        String username = loginFormDTO.getUsername();
        String password = loginFormDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new BizIllegalException("用户名或密码不能为空");
        }
        // 2.查询用户
        User user = lambdaQuery().eq(User::getUsername, username).one();
        if (Objects.isNull(user)) {
            throw new BizIllegalException("用户不存在");
        }
        // 3.校验密码
        if (!PasswordEncoder.matches(password, user.getPassword())) {
            throw new BizIllegalException("用户名或密码错误");
        }
        // 4.返回
        return BeanUtils.copyBean(user, UserLoginVO.class);
    }

    @Override
    public void deductMoney(String pw, Integer amount) {
        // 1.校验密码
        User user = lambdaQuery().eq(User::getId, 1L).one();
        if (!PasswordEncoder.matches(pw, user.getPassword())) {
            throw new BizIllegalException("密码错误");
        }
        // 2.校验余额
        if (user.getBalance() < amount) {
            throw new BizIllegalException("余额不足");
        }
        // 3.扣减余额
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, user.getId()).ge(User::getBalance, amount);
        userMapper.deductMoney(wrapper, amount);
        // 4.校验是否扣减成功
        user = lambdaQuery().eq(User::getId, user.getId()).one();
        if (user.getBalance() < 0) {
            throw new BizIllegalException("扣减失败，余额不足");
        }
    }
}